// pages/artifactCard/artifactCard.js
var app = getApp();
const PAGE_SIZE = 7;

Page({
  data: {
    page: 1,
    pageTotal: 1,
    artifacts: [{
      id: 0,
      name: "",
      category: 0,
      material: 0,
      weight: 0,
      length: 0,
      width: 0,
      height: null,
      year: 0,
      yearDescription: "",
      description: "",
      imageUrl: "",
    }],
    showDialog: false,
  },

  onLoad(options) {
    this.dialogBox = this.selectComponent("#dialogBox")
    this.refresh()
  },

  handleSearch () {
    this.setData({'showDialog': true})
  },

  onConfirm (e) {
    this.setData({'showDialog': false})
    const data = e.detail
    console.log("confirm event:", data)
    // this.refresh()
  },

  onCancel () {
    this.setData({'showDialog': false})
  },

  handleReset () {
    this.setData({'page': 1})
    this.selectComponent("#dialogBox").resetData()
    this.refresh()
  },

  viewDetails(e) {
    const artifactId = e.currentTarget.id;
    wx.navigateTo({
      url: '../cardDetail/cardDetail?artifactId=' + artifactId,
    })
  },

  refresh() {
    let getPageUrl = '/admin-api/artifact/info/page'
    let postData = {
      pageNo: this.data.page,
      pageSize: PAGE_SIZE
    }
    app.func.req(getPageUrl, postData, (res) => {
      const pageTotal = Math.ceil(res.data.total / PAGE_SIZE)
      for (let i = 0; i < res.data.list.length; i++) {
        res.data.list[i].imageUrl = ""
        let getImageUrl = "/admin-api/artifact/info/info-image/list-by-artifact-id"
        app.func.req(getImageUrl, {artifactId: res.data.list[i].id}, (res) => {
          if (Array.isArray(res.data) && res.data.length) {
            this.setData({['artifacts[' + i + '].imageUrl']: res.data[0].imagePath})
          }
        })
      }
      this.setData({'artifacts': res.data.list, 'pageTotal': pageTotal})
    })
  },

  handlePageChange(e) {
    if (!e.detail.touchEnabled) {
      return
    }
    this.setData({'page': e.detail.currentIndex})
    this.refresh()
    // console.log("page changed", e.detail)
  }
})